package com.epmis.epmis.Service.impl;


import com.epmis.epmis.Mapper.ExamineMapper;
import com.epmis.epmis.Mapper.MissionMapper;
import com.epmis.epmis.Mapper.ProjectMapper;
import com.epmis.epmis.Mapper.UserMapper;
import com.epmis.epmis.Service.ExamineService;
import com.epmis.epmis.pojo.*;
import com.epmis.epmis.utils.ImageUitl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.goeasy.GoEasy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExamineServiceImpl implements ExamineService {
    @Resource
    ExamineMapper examineMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    MissionMapper missionMapper;
    @Resource
    ProjectMapper projectMapper;


    @Override
    public PageInfo<HashMap<String, Object>> findMyApplicant(int pageCode, int pageSize, int id) {
        PageHelper.startPage(pageCode,pageSize);
        List<Examine> examines = examineMapper.findMyApplicant(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PageInfo pageInfo = new PageInfo<>(examines);
        List<Examine> examine = pageInfo.getList();
        List<HashMap<String,Object>> list = examine.stream().map(res -> {
            HashMap<String,Object> newMap = new HashMap<>();
            newMap.put("id",res.getId());
            newMap.put("number",res.getNumber());
            User user = userMapper.getUserMessage(res.getApplicant_id());
            newMap.put("apply",user.getName());
            newMap.put("status",res.getState());
            try {
                newMap.put("circleUrl","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(user.getPhoto()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            newMap.put("date",sdf.format(res.getDate()));
            return newMap;
        }).collect(Collectors.toList());
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public PageInfo<HashMap<String, Object>> findMyApplicantComplete(int pageCode, int pageSize, int id) {
        PageHelper.startPage(pageCode,pageSize);
        List<Examine> examines = examineMapper.findMyApplicantComplete(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PageInfo pageInfo = new PageInfo<>(examines);
        List<Examine> examine = pageInfo.getList();
        List<HashMap<String,Object>> list = examine.stream().map(res -> {
            HashMap<String,Object> newMap = new HashMap<>();
            newMap.put("id",res.getId());
            newMap.put("number",res.getNumber());
            User user = userMapper.getUserMessage(res.getApplicant_id());
            newMap.put("apply",user.getName());
            newMap.put("status",res.getState());
            try {
                newMap.put("circleUrl","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(user.getPhoto()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            newMap.put("date",sdf.format(res.getDate()));
            return newMap;
        }).collect(Collectors.toList());
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public PageInfo<HashMap<String, Object>> SearchMyApplicant(int pageCode, int pageSize, int id, String content) {
        PageHelper.startPage(pageCode,pageSize);
        HashMap<String,Object> map = new HashMap();
        map.put("id",id);
        map.put("content",content);
        List<Examine> examines = examineMapper.SearchMyApplicant(map);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PageInfo pageInfo = new PageInfo<>(examines);
        List<Examine> examine = pageInfo.getList();
        List<HashMap<String,Object>> list = examine.stream().map(res -> {
            HashMap<String,Object> newMap = new HashMap<>();
            newMap.put("id",res.getId());
            newMap.put("number",res.getNumber());
            User user = userMapper.getUserMessage(res.getApplicant_id());
            newMap.put("apply",user.getName());
            newMap.put("status",res.getState());
            try {
                newMap.put("circleUrl","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(user.getPhoto()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            newMap.put("date",sdf.format(res.getDate()));
            return newMap;
        }).collect(Collectors.toList());
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public PageInfo<HashMap<String, Object>> findMyExamine(int pageCode, int pageSize, int id) {
        PageHelper.startPage(pageCode,pageSize);
        List<Examine> examines = examineMapper.findMyExamine(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PageInfo pageInfo = new PageInfo<>(examines);
        List<Examine> examine = pageInfo.getList();
        List<HashMap<String,Object>> list = examine.stream().map(res -> {
            HashMap<String,Object> newMap = new HashMap<>();
            newMap.put("id",res.getId());
            newMap.put("number",res.getNumber());
            User user = userMapper.getUserMessage(res.getApplicant_id());
            newMap.put("apply",user.getName());
            newMap.put("status",res.getState());
            try {
                newMap.put("circleUrl","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(user.getPhoto()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            newMap.put("date",sdf.format(res.getDate()));
            return newMap;
        }).collect(Collectors.toList());
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public PageInfo<HashMap<String, Object>> findMyExamineComplete(int pageCode, int pageSize, int id) {
        PageHelper.startPage(pageCode,pageSize);
        List<Examine> examines = examineMapper.findMyExamineComplete(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PageInfo pageInfo = new PageInfo<>(examines);
        List<Examine> examine = pageInfo.getList();
        List<HashMap<String,Object>> list = examine.stream().map(res -> {
            HashMap<String,Object> newMap = new HashMap<>();
            newMap.put("id",res.getId());
            newMap.put("number",res.getNumber());
            User user = userMapper.getUserMessage(res.getApplicant_id());
            newMap.put("apply",user.getName());
            newMap.put("status",res.getState());
            try {
                newMap.put("circleUrl","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(user.getPhoto()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            newMap.put("date",sdf.format(res.getDate()));
            return newMap;
        }).collect(Collectors.toList());
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public PageInfo<HashMap<String, Object>> SearchMyExamine(int pageCode, int pageSize, int id, String content) {
        PageHelper.startPage(pageCode,pageSize);
        HashMap<String,Object> map = new HashMap();
        map.put("id",id);
        map.put("content",content);
        List<Examine> examines = examineMapper.SearchMyExamine(map);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PageInfo pageInfo = new PageInfo<>(examines);
        List<Examine> examine = pageInfo.getList();
        List<HashMap<String,Object>> list = examine.stream().map(res -> {
            HashMap<String,Object> newMap = new HashMap<>();
            newMap.put("id",res.getId());
            newMap.put("number",res.getNumber());
            User user = userMapper.getUserMessage(res.getApplicant_id());
            newMap.put("apply",user.getName());
            newMap.put("status",res.getState());
            try {
                newMap.put("circleUrl","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(user.getPhoto()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            newMap.put("date",sdf.format(res.getDate()));
            return newMap;
        }).collect(Collectors.toList());
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public HashMap<String, Object> getExamineMessages(int id) {
        Examine examine = examineMapper.getExamineMessage(id);
        List<ExamineProcess> examineProcesses = examineMapper.getExamineProcess(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        User applicant = userMapper.getUserMessage(examine.getApplicant_id());
        HashMap<String,Object> map = new HashMap<>();
        map.put("applicantName",applicant.getName());
        map.put("applicantId",applicant.getId());
        map.put("examineId",id);
        try {
            map.put("applicantHead","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(applicant.getPhoto()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("applicantDepartment",userMapper.getDepartmentName(applicant.getDepartment_id()).getDepart_name());
        map.put("applicantPost",userMapper.getPostName(applicant.getPost_id()).getPost_name());
        map.put("applicantTime",sdf.format(examine.getDate()));
        map.put("status",examine.getState());
        map.put("number",examine.getNumber());
        map.put("content",examine.getContent());
        if(examine.getDetail() == null){
            map.put("detail","");
        }else{
            map.put("detail",examine.getDetail());
        }
        List<Accessory> files = examineMapper.getExamineFiles(id);
        List<ExamineProcess> examineProcesses1 = examineMapper.getExamineCurrentProcess(id);
        if(examineProcesses1.size() != 0){
            User CurrentExamineP = userMapper.getUserMessage(examineProcesses1.get(0).getExamine_p_id());
            map.put("currentExamineName",CurrentExamineP.getName());
            map.put("currentExamineId",CurrentExamineP.getId());
            try {
                map.put("currentExaminePHead","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(CurrentExamineP.getPhoto()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        map.put("files",files);
        List<HashMap<String,Object>> process = examineProcesses.stream().map(res -> {
            HashMap<String,Object> newMap = new HashMap<>();
            newMap.put("id",res.getId());
            User examineP = userMapper.getUserMessage(res.getExamine_p_id());
            newMap.put("examinePName",examineP.getName());
            newMap.put("status",res.getState());
            try {
                newMap.put("examinePHead","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(examineP.getPhoto()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(res.getDate() == null){
                newMap.put("date","");
            }else{
                newMap.put("date",res.getDate());
            }
            return newMap;
        }).collect(Collectors.toList());
        map.put("process",process);
        return map;
    }

    @Override
    public int createExamineComment(HashMap<String, Object> map) {
        GoEasy goEasy = new GoEasy("rest-hangzhou.goeasy.io","BC-f92a140e428c4ce79442bafc26e543d8");
        Comment comment = new Comment();
        Date date = new Timestamp((new java.util.Date()).getTime());
        if((int)map.get("replyCommentId") != 0){
            int replyUserId = missionMapper.getComment((int)map.get("replyCommentId")).getIssuer_id();
            User Isuser = userMapper.getUserMessage(Integer.valueOf((String) map.get("userId")));
            Notification notification = new Notification();
            notification.setContent((String)map.get("content"));
            notification.setActivity("回复了你的评论");
            notification.setType("评论");
            notification.setDate(date);
            notification.setIssuer_name(Isuser.getName());
            notification.setIssuer_photo(Isuser.getPhoto());
            notification.setIssuer_id(Isuser.getId());
            notification.setRecipient_id(replyUserId);
            notification.setEnterprise_id(Integer.valueOf((String)map.get("enterpriseId")));
            userMapper.createNotification(notification);
            goEasy.publish(String.valueOf(replyUserId), "您有一条关于评论的新消息，请到消息查看详情");
        }
        comment.setComment_date(date);
        comment.setIssuer_id(Integer.valueOf((String) map.get("userId")));
        comment.setContent((String)map.get("content"));
        comment.setEnterprise_id(Integer.valueOf((String)map.get("enterpriseId")));
        comment.setExamine_id((int)map.get("id"));
        return examineMapper.createExamineComment(comment);
    }

    @Override
    public int deleteExamineComment(int id) {
        return examineMapper.deleteExamineComment(id);
    }

    @Override
    public int createExamineActivity(int id,int enterpriseId,int userId) {
        Activity activity = new Activity();
        activity.setEnterprise_id(enterpriseId);
        activity.setUpdate_p_id(userId);
        activity.setExamine_id(id);
        activity.setUpdate_after("查阅了审批");
        Date date = new Timestamp((new java.util.Date()).getTime());
        activity.setUpdate_date(date);
        return examineMapper.createExamineActivity(activity);
    }

    @Override
    public List<HashMap<String,Object>> getExamineActivity(int id) {
        List<Activity> activities = examineMapper.getExamineActivity(id);
        List<HashMap<String,Object>> list = activities.stream().map(res -> {
            HashMap<String,Object> newMap = new HashMap<>();
            User user = userMapper.getUserMessage(res.getUpdate_p_id());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newMap.put("name",user.getName());
            newMap.put("content",res.getUpdate_after());
            newMap.put("date",sdf.format(res.getUpdate_date()));
            newMap.put("id",res.getId());
            newMap.put("apply",user.getName());
            try {
                newMap.put("headImageUrl","data:image/jpeg;base64,"+ ImageUitl.ImageToBase64ByLocal(user.getPhoto()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return newMap;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public int agreeExamine(int id, int userId,int enterpriseId) {
        GoEasy goEasy = new GoEasy("rest-hangzhou.goeasy.io","BC-f92a140e428c4ce79442bafc26e543d8");
        Examine examine = examineMapper.getExamineMessage(id);
        User user = userMapper.getUserMessage(examine.getApplicant_id());
        Date date = new Timestamp((new java.util.Date()).getTime());
        Notification notification = new Notification();
        notification.setContent("审批编号: " + examine.getNumber());
        notification.setActivity("同意了该审批");
        notification.setType("审批");
        notification.setDate(date);
        notification.setIssuer_name(user.getName());
        notification.setIssuer_photo(user.getPhoto());
        notification.setIssuer_id(user.getId());
        notification.setRecipient_id(userId);
        notification.setEnterprise_id(enterpriseId);
        goEasy.publish(String.valueOf(userId), "您有一条关于审批的新消息，请到消息查看详情");
        userMapper.createNotification(notification);
        ExamineProcess examineProcess  = examineMapper.getExamineUserProcess(id,userId);
        if(examineProcess.getNext_p_id() == 0){
            HashMap<String,Object> map = new HashMap<>();
            map.put("state","已通过");
            map.put("id",id);
            examineMapper.updateExamineState(map);
            if(examine.getType() == 0){
                String projectNumber = examine.getDetail().split(",")[1].split("项目编号")[1];
                HashMap<String,Object> project = new HashMap<>();
                project.put("state","正常");
                project.put("number",projectNumber);
                project.put("enterpriseId",enterpriseId);
                projectMapper.updateProjectStateByNumber(map);
            }else if(examine.getType() == 1){
                int missionId = Integer.valueOf(examine.getDetail().split(",")[1].split("任务编号")[1]);
                missionMapper.updateMissionStatus(0,missionId);
            }
        }else {
            notification.setActivity("轮到你审批了");
            notification.setRecipient_id(examineProcess.getExamine_p_id());
            goEasy.publish(String.valueOf(examineProcess.getExamine_p_id()), "您有一条关于审批的新消息，请到消息查看详情");
            userMapper.createNotification(notification);
        }
        return examineMapper.agreeExamine(id,userId);
    }

    @Override
    public int backExamine(int id,int enterpriseId) {
        HashMap<String,Object> map = new HashMap<>();
        map.put("state","已撤销");
        map.put("id",id);
        Examine examine = examineMapper.getExamineMessage(id);
        if(examine.getType() == 0){
            String projectNumber = examine.getDetail().split(",")[1].split("项目编号")[1];
            HashMap<String,Object> project = new HashMap<>();
            project.put("number",projectNumber);
            project.put("enterpriseId",enterpriseId);
            projectMapper.deleteProjectByNumber(map);
        }else if(examine.getType() == 1){
            int missionId = Integer.valueOf(examine.getDetail().split(",")[1].split("任务编号")[1]);
            Mission mission = missionMapper.getMission(missionId);
            missionMapper.deleteRelMission(missionId);
            if(mission.getType().equals("项目费用")){
                missionMapper.deleteCost(missionId);
            }else if(mission.getType().equals("项目目标")){
                missionMapper.deleteTarget(missionId);
            }else{
                missionMapper.deleteMissionProject(missionId);
            }
        }
        return examineMapper.updateExamineState(map);
    }

    @Override
    public int refuseExamine(int id, int userId,int enterpriseId) {
        HashMap<String,Object> map = new HashMap<>();
        map.put("state","已回拒");
        map.put("id",id);
        examineMapper.updateExamineState(map);
        Examine examine = examineMapper.getExamineMessage(id);
        if(examine.getType() == 0){
            String projectNumber = examine.getDetail().split(",")[1].split("项目编号")[1];
            HashMap<String,Object> project = new HashMap<>();
            project.put("number",projectNumber);
            project.put("enterpriseId",enterpriseId);
            projectMapper.deleteProjectByNumber(map);
        }else if(examine.getType() == 1){
            int missionId = Integer.valueOf(examine.getDetail().split(",")[1].split("任务编号")[1]);
            Mission mission = missionMapper.getMission(missionId);
            missionMapper.deleteRelMission(missionId);
            if(mission.getType().equals("项目费用")){
                missionMapper.deleteCost(missionId);
            }else if(mission.getType().equals("项目目标")){
                missionMapper.deleteTarget(missionId);
            }else{
                missionMapper.deleteMissionProject(missionId);
            }
        }
        return examineMapper.refuseExamine(id,userId);
    }


    @Override
    public int noticeExamine(int userId,int getId,int id,int enterpriseId) {
        GoEasy goEasy = new GoEasy("rest-hangzhou.goeasy.io","BC-f92a140e428c4ce79442bafc26e543d8");
        User user = userMapper.getUserMessage(userId);
        Date date = new Timestamp((new java.util.Date()).getTime());
        Examine examine = examineMapper.getExamineMessage(id);
        Notification notification = new Notification();
        notification.setContent("审批编号: " + examine.getNumber());
        notification.setActivity("提醒你查看该审批");
        notification.setType("审批");
        notification.setDate(date);
        notification.setIssuer_name(user.getName());
        notification.setIssuer_photo(user.getPhoto());
        notification.setIssuer_id(user.getId());
        notification.setRecipient_id(getId);
        notification.setEnterprise_id(enterpriseId);
        goEasy.publish(String.valueOf(getId), "您有一条关于审批的新消息，请到消息查看详情");
        return userMapper.createNotification(notification);
    }

    @Override
    public int deleteExamine(int id) {
        examineMapper.deleteExamineActivity(id);
        examineMapper.deleteExamineAllComment(id);
        examineMapper.deleteExamineFile(id);
        examineMapper.deleteExamineProcess(id);
        return examineMapper.deleteExamine(id);
    }


}
